package vip.zhenzicheng.websocket.websocket.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * J2EE方式，利用Tomcat
 *
 * @author zhenzicheng
 * @date 2023-03-20 11:46
 */
@Component
// 类似 @RequestMapping，放入 WS 服务器监听的 URL
@ServerEndpoint(value = "/ws/j2ee/{firstMsg}")
@Slf4j
public class WebSocketServer {

    /**
     * 第一次建立连接
     *
     * @param msg 可以类似于 @PathVariable 注解，可以直接获取 URL 中的变量值
     */
    @OnOpen
    public void onOpen(Session session, @PathParam(value = "firstMsg") String msg) throws IOException {
        session.getBasicRemote().sendText("连接已建立");
        log.info("首次连接消息为:{}", msg);
    }

    /**
     * 接收到客户端发送的消息
     */
    @OnMessage
    public void onMessage(Session session, String message) throws IOException {
        log.info("收到客户端消息:{}", message);
        session.getBasicRemote().sendText("服务端收到消息:" + message);
    }

    @OnMessage
    public void onMessage(Session session, byte[] message) {
        log.info("收到二进制消息:" + new String(message, StandardCharsets.UTF_8));
    }

    /**
     * 客户端主动断开时
     */
    @OnClose
    public void onClose(Session session) throws IOException {
        // 通过 @OnClose 注解不能在关闭时再给客户端发消息
        // session.getBasicRemote().sendText("closed");
        log.info("连接已断开");
    }
}
